import http from './interface'
import CryptoJS from 'crypto-js'
import {
	BaseApi,
	Appid,
	Secret
} from '@/components/kevinrong-http/baseApi'
export const $http = (url, method, data, json) => {

	http.interceptor.request = async (config) => {

		let nonce = generateRandomID(),
			t = new Date().getTime(),
			userInfo = uni.getStorageSync('userInfo'),
			XTOKEN='';
		if (userInfo?.token) {
			XTOKEN = userInfo.token
		}
		config.header = {
			'appid': Appid,
			'nonce': nonce,
			't': t,
			sign: getSign(nonce, t, Secret),
			'content-type': 'application/x-www-form-urlencoded',
			"x-token": XTOKEN
		}
	}
	//设置请求结束后拦截器
	http.interceptor.response = async (response) => {

		// if (response.data.code == '-105') { //token失效
		// 	return response.data = await doRequest(response, url) //动态刷新token,并重新完成request请求
		// }
		return response;
	}
	return http.request({
		method: method,
		url: url,
		dataType: 'json',
		data,
	})
}

function generateRandomID() {
	const characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
	const idLength = 30; // 字符串长度 这里生成30位的
	let randomID = '';

	for (let i = 0; i < idLength; i++) {
		const randomIndex = Math.floor(Math.random() * characters.length);
		randomID += characters.charAt(randomIndex);
	}

	return randomID;
}

function getSign(nonce, t, secret) {
	let sha256 = CryptoJS.HmacSHA256(nonce + t + secret,'discuz').toString();
	let base64_sign = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(sha256));
	return base64_sign;
}
async function login() {
	//返回环宇token所需的login code
	return new Promise(resolve => {
		uni.login({
			provider: 'weixin',
			success(loginRes) {
				resolve(loginRes.code)
			},
			fail() {}
		});
	})
}

async function doRequest(response, url) {

	var res = await get('api/restful/?/token')
	if (res && res.data.token) {
		let config = response.config
		uni.setStorageSync("token", res.data.token);
		config.header['token'] = res.data.token
		let json = config.header["Content-Type"] === 'application/json'
		const resold = await $http(url, config.method, {
			...config.data
		}, json)
		return resold
	} else {
		uni.clearStorage()
		return false
	}
}
async function getToken() {
	// var res = await post('api/restful/?/token')
	console.log(res)
}

export function postJson(url, data) {
	return $http(url, 'POST', data)
}
export function get(url, data) {
	return $http(url, 'GET', data)
}
export function post(url, data) {
	return $http(url, 'POST', data, true)
}